var mi = {}; //密友圈名字空间
(function(mi) {
    var utils = {
        getQuery: function(a) {
            var b = arguments[1] || window.location.search,
                c = new RegExp("(^|&)" + a + "=([^&]*)(&|$)"),
                d = b.substr(b.indexOf("?") + 1).match(c);
            return null != d ? d[2] : ""
        },
        namespace: function(str) {
            for (var arr = str.split(","), i = 0, len = arr.length; len > i; i++)
                for (var arrJ = arr[i].split("."), parent = {}, j = 0, jLen = arrJ.length; jLen > j; j++) {
                    var name = arrJ[j],
                        child = parent[name];
                    0 === j ? eval("(typeof " + name + ')==="undefined"?(' + name + '={}):"";parent=' + name) : parent = parent[name] = "undefined" == typeof child ? {} : child
                }
        },
        urlReplace: function(a, b) {
            var c = b.url || location.search.substring(1),
                d = new RegExp("(^|&)(" + a + "=)([^&]*)"),
                e = b.content ? b.content : "";
            return c.replace(d, function(a, b, c) {
                return e ? b + c + e : ""
            })
        },
        isWeiXin: function() {
            var ua = window.navigator.userAgent.toLowerCase();
            return ua.match(/MicroMessenger/i) == 'micromessenger';
        },
        getCookie: function(a) {
            var b = new RegExp("(^| )" + a + "(?:=([^;]*))?(;|$)"),
                c = document.cookie.match(b);
            return c ? c[2] ? unescape(c[2]) : "" : null
        },
        delCookie: function(a, b, c, d) {
            var e = utils.getCookie(a);
            if (null != e) {
                var f = new Date;
                f.setMinutes(f.getMinutes() - 1e3), b = b || "/", document.cookie = a + "=;expires=" + f.toGMTString() + (b ? ";path=" + b : "") + (c ? ";domain=" + c : "") + (d ? ";secure" : "")
            }
        },
        setCookie: function(a, b, c, d, e, f) {
            var g = new Date,
                c = arguments[2] || null,
                d = arguments[3] || "/",
                e = arguments[4] || null,
                f = arguments[5] || !1;
            c ? g.setMinutes(g.getMinutes() + parseInt(c)) : "", document.cookie = a + "=" + escape(b) + (c ? ";expires=" + g.toGMTString() : "") + (d ? ";path=" + d : "") + (e ? ";domain=" + e : "") + (f ? ";secure" : "")
        }
    };
    /**
     * [PRODUCT_ORDERDETAIL 订单详情]
     * @type {Object}
     */
    mi.PRODUCT_ORDERDETAIL = {
        init: function() {
            this.initPageBtn();
        },
        initPageBtn: function() {
            var a = [];
            switch (window.dealStatus) {
                case 1:
                    a.push('<div class="mod_cell ui_p10"><div class="qb_flex">'), a.push($("#cancel-tpl").html()), a.push($("#topay-tpl").html()), a.push("</div></div>");
                    break;
                case 2:
                    2 == window.payType && (a.push('<div class="qb_flex qb_mb10 ui_gap">'), a.push($("#cancel-tpl").html()), a.push("</div>")), 1 == window.payType && a.push($("#drawback-tpl").html());
                    break;
                case 3:
                    2 == window.payType ? $("#suc-msg").removeClass("qb_none") : (a.push('<div class="qb_flex qb_mb10 ui_gap">'), a.push($("#recv-tpl").html()), a.push("</div>"));
                    break;
                case 7:
                    a.push($("#onback-tpl").html().replace(/{#text#}/, "退款中..."));
                    break;
                case 8:
                    a.push($("#onback-tpl").html().replace(/{#text#}/, "退款完成"));
                    break;
                case 18:
                    break;
                case 19:
                    a.push($("#cancelgoods-tpl").html())
            }
            $("#operate_area").html(a.join(""))
        }
    };

    mi.PRODUCT_ADDRESS = {
        init: function() {
            this._initValidate();
        },
        _initValidate: function() {
            var me = this;
            var config = {};
            config = {
                "name": {
                    rule: {
                        required: {
                            message: "请填写收件人姓名"
                        }
                    },
                    pos: "bottom"
                },
                "mobile": {
                    rule: {
                        required: {
                            message: "请填写联系电话"
                        },
                        mobile: {
                            message: "请输入11位手机号码"
                        }
                    },
                    pos: "bottom"
                },
                "address": {
                    rule: {
                        required: {
                            message: "请填写详细地址"
                        }
                    },
                    pos: "bottom"
                }
            }
            var va = new Validate("page_address_add", config);
            $("#save_addr").tap(function() {
                va.validate(function(result) {
                    if (result) {
                        me.save();
                    }
                });
            });
        },
        save: function() {
            var fullName = $('#name').val();
            var phone = $('#mobile').val();
            var address = $('#address').val();
            var data = {
                "fullname": $.trim((fullName || "").replace(/s+/g, "")),
                "phone": $.trim((phone || "").replace(/s+/g, "")),
                "address": $.trim((address || "").replace(/s+/g, "")),
                "deliverytype":"delivery"
            }
            var p = {
                'module': 'product',
                'method': 'updateUserInfo',
                'params': JSON.stringify(data)
            };
            $.ajax({
                url: window.basePath,
                dataType: "json",
                type: "POST",
                data: p,
                success: function(d) {
                    var params = {
                        "type": "buy",
                        "sid": -1,
                        "tplid": window.tplid,
                        "id": window.preOid
                    }

                    if (window.rootId) {
                        params["rootid"] = rootId;
                    }
                    url = '&module=product&method=getOrderDetail&force=1&params=';
                    url = url + JSON.stringify(params);
                    location.href = window.hrefPath + url;
                }
            });
        }
    };
    mi.PRODUCT_DETAIL = {
        propList: [],
        matchProperty: [],
        buyProperty: "",
        selectedCount: 0,
        init: function(id) {
            this.id = id;
            this._initParam();
            this._initClickEvent();
            this._addFavorite(id);
            this.getCartGoodsNum();
        },
        _initParam: function() {
            this.buyProperty = "";
            this.errorMsg = "";
            this._initStock(), (window.inventory == 0 || window.sku.length > 0) && this._initProperty();
            (window.inventory == 1 && window.totalInventoryCount == 0 && window.sku.length == 0) && ($("#add-cart").addClass("btn_disabled") && $("#buy-now").addClass("btn_disabled") && $("#buy-now").removeClass("btn_strong"));
        },
        _initStock: function() {
            var a = this;
            $.each(window.availSku, function(b) {
                a.propList.push(b)
            });
        },
        getCartGoodsNum: function() {
            var customerId = $.util.getParam("customerId");
            $.req.get("call.json?module=product&customerId=" + customerId + "&method=getCarNum", {
                userName: buyParams.userName,
                params: {
                    "type": "buy",
                    "sid": "-1"
                }
            }, function(data) {
                if (!data.code) {
                    $("#carNum").text(data.total || 0).data("num", data.total);
                    detail.cartList = data.list;
                    if (data && data.total > 0) {
                        $("#car").addClass("to-car");
                    } else {
                        $("#car").removeClass("to-car");
                    }
                }
            });
        },
        _initPropertyEvent: function(e) {
            var b = $(e);
            if (!b.hasClass("current") && !b.hasClass("disabled")) {
                b.addClass("current").siblings().removeClass("current");
                var c = b.parent();
                this.loopProp(b.attr("data-value"), c.attr("index"), c.attr("skuName"))
            }
            if (b.parents('.mod_property').hasClass("free-list")) {
                var pnum = Math.ceil($.util.accSub(window.price, b.data("value")));
                var num = $("#buyNum").val();
                pnum = num * pnum;
                if (pnum) {
                    $("#invitation").html("需要"+pnum+"个好友鼎力支持");
                } else {
                    $("#invitation").html("正常价格，可直接购买。");
                }
                $("#invitation").show();
            }
        },
        _initProperty: function() {
            var a = this,
                b = window.sku,
                c = $("#prop-tpl").html(),
                d = '<span data-value="{#key#}" class="{#className#}">{#optionName#}</span>',
                d1 = '<span data-value="{#key#}" class="property {#className#}"><img src="{#url#}" ><label>{#optionName#}</label></span>',
                e = [],
                f = [],
                g = {};

            b.forEach(function(b, h) {
                if (b.pUrl[0]) {
                    var i = [];
                    b.pList.forEach(function(a, n) {
                        var c,
                            f = b.pUrl[n];
                        c = d1.replace(/{#key#}/, a).replace(/{#url#}/, f).replace(/{#optionName#}/, a).replace(/{#className#}/, 1 === b.pList.length ? "current" : ""), i.push(c);
                    });
                    1 == b.pList.length ? (g.key || (g.key = b.pList[0], g.index = h,
                            g.propName = b.pName), a.matchProperty[h] = b.pList[0],
                        a.selectedCount++) : f.push(b.pName);
                    e.push(c.replace(/{#index#}/, h).replace(/{#propClass#}/, "property").replace(/{#pName#}/g,
                        b.pName).replace(/{#pList#}/, i.join("")).replace(/{#availSku#}/, b.availSku));
                } else {
                    var i = [];
                    b.pList.forEach(function(a) {
                        var c, e = a;
                        c = d.replace(/{#key#}/, e).replace(/{#optionName#}/, a).replace(/{#className#}/, 1 === b.pList.length ? "current" : ""), i.push(c);
                    });
                    1 == b.pList.length ? (g.key || (g.key = b.pList[0], g.index = h,
                            g.propName = b.pName), a.matchProperty[h] = b.pList[0],
                        a.selectedCount++) : f.push(b.pName);
                    e.push(c.replace(/{#index#}/, h).replace(/{#propClass#}/, "").replace(/{#pName#}/g,
                        b.pName).replace(/{#pList#}/, i.join("")).replace(/{#availSku#}/, b.availSku));
                }
            });
            $('#buyNum').prop('disabled', true);
            a.errorMsg = "请选择" + f.join("/"), $("#prop-list").html(e.join("")),
                a.pNodeList = $(".mod_property"), g.key && a.loopProp(g.key, g.index, g.propName), g = null
        },
        _addFavorite: function() {
            var id = this.id;
            $("#favorite").tap(function() {
                var me = $(this);
                var favorite = $(this).attr("favorite");
                var customerId = $.util.getParam("customerId");
                if (favorite == "0") {
                    var method = "addFavorite";
                } else {
                    var method = "removeFavorite";
                }
                if ($(this).hasClass("fav1")) {
                    return;
                }
                $("#FavMask").tap(function() {
                    $(this).hide();
                });
                $.util.pageLoading.show();
                $.req.get("call.json?customerId=" + customerId + "&module=product&method=" + method, {
                    params: {
                        "id": id
                    }
                }, function(data) {
                    if (data && !data.code) {
                        if (favorite == "0") {
                            if (!$.util.cookie('isShowFav')) {
                                $("#FavMask").show();
                                $.util.cookie('isShowFav', 1, {
                                    path: "/"
                                });
                            }
                            me.html("已收藏");
                            me.attr("favorite", 1);
                            me.addClass('fav1');
                        } else {
                            me.html("收藏");
                            me.attr("favorite", 0);
                        }
                    }
                    $.util.pageLoading.hide();
                });
            });
        },
        pageSize: 10,
        page: 0,
        _initEvent: function() {
            var me = this;
            $.util.initDataLoading({
                me: mi.PRODUCT_DETAIL,
                lastChildren: function() {
                    return $("#p-comment .main:last");
                },
                page: function() {
                    return mi.PRODUCT_DETAIL.page;
                },
                pageCount: function() {
                    return mi.PRODUCT_DETAIL.pageCount;
                }
            });
        },
        _renderList: function(data, page, callback) {
            var me = this;
            if (data) {
                var html = template("Tpl", data),
                    container = $("#p-comment");
                if (data.code) {
                    container.html(html);
                } else {
                    container.append(html);
                }
                me.page = page;
                me.pageCount = data.pageCount;
                callback && callback();
            }
        },
        _loadList: function(page, callback) {
            var me = this;
            var customerId = $.util.getParam("customerId");
            $.req.get("call.json?customerId=" + customerId + "&module=product&method=getcommentList", {
                params: {
                    "id": me.id,
                    "start": page,
                    "limit": me.pageSize
                }
            }, function(data) {
                if (data) {
                    me._renderList(data, page, callback);
                }
            });
        },
        _initClickEvent: function() {
            var me = this;
            if ((window.inventory == 0 || window.totalInventoryCount > 0 || window.sku.length > 0)) {
                $(".minus,.plus").on("touchend", function(e) {
                    me._initBuyNum(e);
                });
                $(".mod_property span").on("tap", function(e) {
                    if (!$(this).hasClass("current")) {
                        $(".plus").removeClass("disabled");
                    }
                    me._initPropertyEvent(this);
                });
                $("#buy-now,#buy-team").click(function() {
                    if (window.freeBuy == "1") {
                        $("#free-list span.current").removeClass("current");
                        $("#free-list").css({
                            "bottom": 0,
                            "visibility": "visible"
                        });
                        $("#free-list a").click(function() {
                            me._initBuy($(this));
                        });
                    } else {
                        me._initBuy($(this));
                    }
                });
            }
        },
        loopProp: function(a, b, c) {
            var d = [],
                e = !0,
                f = this;
            f.matchProperty[b] || f.selectedCount++, f.matchProperty[b] = a, d[b] = a,
                $.each(window.sku, function(a, b) {
                    var d, g, h = b.pName,
                        i = b.pList,
                        j = f.pNodeList.eq(a),
                        k = j.find("span");
                    h !== c && $.each(i, function(a, b) {

                    })
                });
            f.statisticSelected();
        },
        statisticSelected: function() {
            var a, b, c = this;
            if (c.selectedCount == window.sku.length) {

                if ($('#buyNum').prop('disabled') == true) {
                    $('#buyNum').prop('disabled', false);
                }
                var d = c.matchProperty.join("|");
                c.buyProperty = d;
                a = window.availSku[d];
                if (a) {
                    $("#buyNum").val(1);
                    b = a.inventoryCount;
                    var fixedPrice = a.fixedPrice;
                    var discountedPrice = a.discountedPrice;
                    var miPrice = a.miPrice;
                    if (window.playType != 3 && window.freeBuy != 1 && window.teambuy != 1) {
                        if (window.playType == 5 && window.isEnjoyMiPrice == 1) {
                            $("#price").html("密友价：￥" + miPrice);
                        } else if (discountedPrice > 0) {
                            $("#price").html("￥" + discountedPrice);
                        } else {
                            $("#price").html("￥" + fixedPrice);
                        }
                    }
                    if (parseInt(b) <= 1) {
                        $("#plus").addClass("disabled");
                    }
                    if (parseInt(b)<=0) {
                        $('#inventory_count').show();
                        $("#stock-num").html(b);
                        $(".soldOut").show();
                        if(((window.playType==4&&window.seckillIsStart==1&&window.seckillIsEnd==0)||window.playType!=4)&&$(".add-car").hasClass("btn-disabled") && $("#buy-now").hasClass("btn-disabled")){
                            $("#buy-now").removeClass("btn-disabled");
                            if (window.playType!=4&&window.virtual!=1) {
                                $(".add-car").removeClass("btn-disabled");
                            }
                        }
                    } else {
                        $(".soldOut").hide();
                        $('#inventory_count').hide();
                        if(((window.playType==4&&window.seckillIsStart==1&&window.seckillIsEnd==0)||window.playType!=4)&&$(".add-car").hasClass("btn-disabled") && $("#buy-now").hasClass("btn-disabled")){
                            $("#buy-now").addClass("btn-disabled");
                            if (window.playType!=4&&window.virtual!=1) {
                                $(".add-car").addClass("btn-disabled");
                            }
                        }
                    }
                    $("#buyNum").data("nowKc", b);
                }
                c.curStock = parseInt(b, 10);
				if(((window.playType==4&&window.seckillIsStart==1&&window.seckillIsEnd==0)||window.playType!=4)){
					 if (window.inventory == 1 && b == 0) {
						$("#buy-now").removeClass("btn_strong");
						$("#buy-now").addClass("btn-disabled");
                         if (window.playType!=4&&window.virtual!=1) {
                            $(".add-car").addClass("btn-disabled");
                        }

					}
					if (window.inventory == 1 && b > 0) {
						$("#buy-now").removeClass("btn-disabled");
                        if (window.playType!=4&&window.virtual!=1) {
                            $(".add-car").removeClass("btn-disabled");
                        }
						$("#buy-now").addClass("btn_strong")
					}
				}
            }
        },
        _initBuyNum: function(e) {
            var buyNum = $("#buyNum"),
                target = $(e.target),
                type = target.attr("tag"),
                num = 1 * buyNum.val();
            if (target.hasClass("disabled")) {
                return;
            }

            if (num) {
                if (isNaN(num)) {
                    buyNum.val(1);
                } else {
                    var ktotal = buyNum.data('ktotal') || 999;
                    if ($("#prop-list dl").length != 0) {
                        var size = $("#prop-list dl").eq(0).find("span.current").data("value");
                        var color = $("#prop-list dl").eq(1).find("span.current").data("value");
                        var availSku = $("#prop-list dl").eq(0).data('value');
                        var tmp = decodeURIComponent(availSku);
                        var kc = JSON.parse(eval("'" + tmp + "'"));
                        if ($("#prop-list dl").eq(0).length != 0 && size == null) {
                            return $.util.alert('没有选择规格');
                        }
                        if ($("#prop-list dl").eq(1).length != 0 && color == null) {
                            return $.util.alert('没有选择规格');
                        }
                        ktotal = buyNum.data('nowKc');
                    }
                    if (type == "add") {
                        if ((ktotal && num < parseInt(ktotal)) || (!ktotal && num < 999)) {
                            buyNum.val(++num);
                            $("#sub").removeClass("disabled");
                            if (num > 999 || (ktotal && num > (parseInt(ktotal)) - 1)) {
                                $("#plus").addClass("disabled");
                            }
                        }
                    } else {
                        if (num > 1) {
                            buyNum.val(--num);

                            $("#plus").removeClass("disabled");
                            if (num < 2) {
                                $("#sub").addClass("disabled");
                            }
                        }
                    }
                }
            }

        },
        _initBuy: function($Btn) {
            var customerId = $.util.getParam("customerId");
            if (!$Btn.hasClass("btn-disabled")) {
                if (window.sku.length > 0 && !this.buyProperty)
                    return $.util.alert(this.errorMsg);
                var sizes = '';
                var colors = '';
                var customerId = $.util.getParam("customerId");
                prop = this.buyProperty;
                var params = window.buyParams;
                if (prop != null) {
                    if (window.color != null && window.size != null) {
                        var propItems = prop.split("|");
                        sizes = encodeURIComponent(propItems[0]);
                        colors = encodeURIComponent(propItems[1]);
                    } else if (window.size != null) {
                        sizes = encodeURIComponent(prop);
                    } else if (window.color != null) {
                        colors = encodeURIComponent(prop);
                    }
                    if (sizes) {
                        params.sizes = sizes;
                        params.colors = colors;
                    }
                }
                if ($("#stock-num") && $("#stock-num").html() == 0) {
                    $.util.alert("库存不足");
                    return;
                }
                var teamBuyType = $Btn.data("type");
                if (!$Btn.hasClass("btn-disabled")) {
                    var params = $.extend(params, {
                        "sizes": sizes,
                        "colors": colors,
                        "counts": $("#buyNum").val()
                    });
                    if (window.freeBuy == "1") {
                        if (parseInt(window.freeBuy) && !$("#free-list span").hasClass("current")) {
                            $.util.alert("没有选择价格");
                            return;
                        }
                        params.deposits = $("#free-list span.current").data("value");
                    }
                    $Btn.addClass("btn-disabled");
                    $.util.pageLoading.show();

                    if (window.teamId) {
                        params.teamId = window.teamId; //团购下订单的时候记录订单属于哪个团
                    }
                    if (window.isTeamPro == "1") {
                        params.teamBuyType = teamBuyType;
                    }
                    $.req.get("call.json?customerId=" + customerId + "&module=product&method=preSubmitOrder", {
                        params: params
                    }, function(data) {
                        if (data.hasOwnProperty('code')) {
                            $Btn.removeClass("btn_disabled").removeClass('btn-disabled');
                            $.util.showMsg(data.msg);
                            $.util.pageLoading.hide();
                        } else {
                            var p = {
                                "tplid": 1,
                                "id": data.id
                            }
                            var url = window.hrefPath + '&module=product&method=getOrderDetail&force=1&params=' + encodeURIComponent(JSON.stringify(p));
                            if (window.isTeamPro && teamBuyType == "team") {
                                detail.tuan.createTeamOrder(data.id, function(data) {
                                    if (data && !data.code) {
                                        $.util.pageLoading.hide();
                                        $Btn.removeClass("btn_disabled");
                                        if ($.util.getUa() == 'nativeApp') {
                                            loadUrl(url, "[{key: 'Referer', headerValue: 'http://wx532fcc9ce21e7957.wxtest.mboxone.com'}]")
                                        } else {
                                            location.href = url
                                        }
                                    }
                                });
                            }else {
                                $.util.pageLoading.hide();
                                $Btn.removeClass("btn_disabled");
                                if ($.util.getUa() == 'nativeApp') {
                                    loadUrl(url, "[{key: 'Referer', headerValue: 'http://wx532fcc9ce21e7957.wxtest.mboxone.com'}]")
                                } else {
                                    location.href = url
                                }
                            }
                        }
                    });
                }
            }
        },
        _initSlide: function() {
            var loop = $("#detail-slider li").size() > 2;
            $("#detail-slider").slider({
                loop: loop,
                imgZoom: false,
                arrow: false,
                autoPlay: false,
                slide: function(e, to, from) {
                    var type = $(".ui-slider-item:eq("+to+")").data("type");
                    if(type=='img'){
                        $(".slider_type .img").addClass("curr").siblings(".curr").removeClass("curr");
                    }else{
                        $(".slider_type .video").addClass("curr").siblings(".curr").removeClass("curr");
                    }
                }
            });
            if ($("#detail-slider li").size() > 1) {
                $(".ui-slider-dots").css("marginLeft", $(".ui-slider-dots").width() / 2 * -1);
            } else {
                $(".ui-slider-dots").hide();
            }
        }
    };
    mi.PRODUCT_ORDERPAY = {
        init: function() {
            this._initEvent();
        },
        /**
         * [_initEvent 初始化页面按钮点击事件]
         * @return {[type]}
         */
        _initEvent: function() {
            var me = this;
            $("#toAddrList,#mdAddrBtn").tap(function() {
                me.initAddr();
            });
            $("#submitOrderwxpay").tap(function() {
                var payType = $(this).data("pay-type");
                me.submitOrder(payType);
            });
            $("#submitOrdertenpay").click(function() {
                var payType = $(this).attr("data-pay-type");
                me.submitOrder(payType);
            });
            $("#submitOrdernopay").click(function() {
                var payType = $(this).attr("data-pay-type");
                me.submitOrder(payType);
            });
            $("#submitOrderdelivery").click(function() {
                var payType = $(this).attr("data-pay-type");
                $.util.ok("收到货后，请将货款支付给快递人员。点击确认，即刻为您安排发货！",function(){
                    me.submitOrder(payType);
                });
            });
        },
        test: function() {
            var pa = {
                "id": window.orderId,
                "tplid": 1
            }
            if (window.isTeamPro == "1") {
                pa = {
                    "teamId": window.teamId,
                    "id": window.orderId,
                    "tplid": 1
                }
            }
            $.ajax({
                url: window.basePath,
                dataType: "json",
                type: "POST",
                data: {
                    module: 'product',
                    method: 'sendNotice',
                    params: JSON.stringify(pa)
                },
                success: function() {

                }
            });
        },
        /**
         * [submitOrder 提交订单一键支付]
         * @return {[type]}
         */
        submitOrder: function(payType) {
            var btn = $("#submitOrder" + payType);
            var me = this;
            var remark = {};
            $(".remark").each(function(){
                var oid = $(this).parents("li").find(".serialNumber").data("id");
                remark[oid]=$(this).val();
            });
            var coupon = new Array(0);
            var couponFlag = true;
            $(".coupon").each(function(){
                if($(this).data("couponid")){
                    if(coupon.indexOf($(this).data("couponid"))>=0){
                        $.util.showMsg("同一个优惠券只能在一个订单中使用！");
                        couponFlag=false;
                        return false;
                    }
                    coupon.push($(this).data("couponid"));
                }
            });
            if(!couponFlag){
                return;
            }
            var params = {
                "id": window.orderId,
                "remark": JSON.stringify(remark),
                "sid": window.storeId,
                "type": window.buyType,
                "fullName": (window.fullName || "").replace(/\s+/g, ""),
                "address": (window.address || "").replace(/\s+/g, ""),
                "province": (window.province || "").replace(/\s+/g, ""),
                "city": (window.city || "").replace(/\s+/g, ""),
                "country": (window.country || "").replace(/\s+/g, ""),
                "phone": (window.phone || "").replace(/\s+/g, ""),
                "paytype": payType,
                "dtype": window.deliveryType||"delivery",
                "userCouponId":coupon.join(","),
                "purseMoney":  $(".purseMoney").text()||0,
                'logisticsStatue': window.logisticsStatue,
                'payPasswordToken': window.payPasswordToken,
                bankNumber: $('.ainongpay span').text()
            };
            if (!btn.hasClass("btn_disabled")) {
                if (payType == 'ainongpay' && !/^\d+$/.test($('.ainongpay span').text())) {
                    $.util.alert('请选择银行卡！')
                    return
                }
                //判断收货地址是否为空
                if(window.logisticsStatue!=1){
                    if(window.isActivity==1){
                        if(window.deliveryType=="delivery"){
                            if (window.fullName == '' || window.phone == '') {
                                $.util.showMsg("请填写收货信息");
                                return false;
                            }
                        }else{
                            if(window.fullName==''||window.phone==''){
                                $.util.showMsg("请填写收货信息");
                                return false;
                            }
                            if (window.storeId == ''|| window.storeName == '') {
                                $.util.showMsg("请选择门店");
                                return false;
                            }
                        }
                    }else{
                        if(window.deliveryType=="delivery"){
                            if (window.fullName == '' || window.phone == '' || window.address == ''||window.address=='undefined') {
                                $.util.showMsg("请填写收货信息");
                                return false;
                            }
                        }else{
                            if(window.fullName==''||window.phone==''){
                                $.util.showMsg("请填写收货信息");
                                return false;
                            }
                            if (window.storeId == ''|| window.storeName == '') {
                                $.util.showMsg("请选择门店");
                                return false;
                            }
                        }
                    }
                }
                if(window.proSource==1){
                    if(window.IDName==''||window.IDNumber==''){
                        $.util.showMsg("购买海外商品需要提交真实的身份证信息，海关叔叔才会放行哦");
                        return false;
                    }
                    if(window.IDName!=window.fullName){
                        $.util.showMsg("收货人姓名要和身份证姓名一致哦，不然海关叔叔不放行，宝贝就买不到啦");
                        return false;
                    }
                    var reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
                    if(window.IDNumber.match(reg)==null){
                        $.util.showMsg("身份证号码输入有误");
                        return false;
                    }
                    if(!window.IDPositive||!window.IDBack){
                        $.util.showMsg("请上传身份证正、反面图");
                        return false;
                    }
                    var sealInfo = {
                        "IDName":window.IDName,
                        "IDNumber":window.IDNumber,
                        "IDPositive":window.IDPositive,
                        "IDBack":window.IDBack
                    };
                    params= $.extend({},params,sealInfo);
                }
                $.util.pageLoading.show("加载中");
                btn.addClass("btn_disabled");
                $.ajax({
                    url: window.basePath,
                    dataType: "json",
                    type: "POST",
                    data: {
                        module: 'product',
                        method: 'submitOrder',
                        params: JSON.stringify(params)
                    },
                    success: function(data) {
                        $.util.pageLoading.hide();
                        if (payType == 'ainongpay') {
                            location.href=data.url;
                            return
                        }
                        if (data.mweb_url) {
                            window.wxId = data.id;
                            var p = {
                                "id": data.id,
                                "tplid": 1
                            }
                            var url = data.mweb_url + '&redirect_url=' + encodeURIComponent(window.baseUrl + window.hrefPath + '&redirect=1&module=product&method=getOrderDetail&params=' + encodeURIComponent(JSON.stringify(p)));
                            var ifr = document.createElement("iframe"); 
                            ifr.setAttribute('src', url); 
                            ifr.setAttribute('style', 'display:none'); 
                            document.body.appendChild(ifr); 
                            $.util.pageLoading.show();
                            setTimeout(function() {
                                $.util.pageLoading.hide();
                                $('.mask').show();
				                $('.h5-pay-layer').show();
                            }, 2000)
                            return;
                        } else if (typeof(data.code) !== "undefined") {
                            btn.removeClass("btn_disabled");
                            $.util.showMsg(data.msg);
                            return;
                        }
                        if (window.buyType == "point") {
                            var p = {
                                "id": data.id,
                                "tplid": 1
                            }
                            location.href = window.hrefPath + '&module=point&method=pointSuccess&params=' + JSON.stringify(p);
                            return;
                        }
                        var price = data.price;
                        if(price<=0){
                            me.sendNotice();
                            return;
                        }
                        if (payType == "nopay") {
                            var p = {
                                "id": data.id,
                                "tplid": 1
                            }
                            location.href = window.hrefPath + '&module=product&method=orderSuccess&params=' + JSON.stringify(p);
                            return;
                        }
                        if (payType == "wxpay") {
                            try {
                                WeixinJSBridge.invoke('getBrandWCPayRequest', data.pkg, function(res) {
                                    if (res.err_msg == 'get_brand_wcpay_request:ok') {
                                        //发送模板消息
                                        me.sendNotice();
                                    } else {
                                        btn.removeClass("btn_disabled");
                                        me.cancelOrder(function() {
                                            if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                                                return $.util.alert("操作已取消");
                                            } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
                                                return $.util.alert("网络错误发送失败，请稍后再试");
                                            } else if (res.err_msg == 'access_control:not_allow' || res.err_msg == 'system:access_denied') {
                                                return $.util.alert("商家尚未开通微信支付");
                                            } else {
                                                return $.util.alert(res.err_msg);
                                            }
                                        });
                                    }
                                });
                            } catch (e) {
                                me.cancelOrder(function() {
                                    btn.removeClass("btn_disabled");
                                    return $.util.alert("操作失败，请确保在微信浏览器中操作");
                                });
                            }
                        } else if (payType == "tenpay") {
                            btn.removeClass("btn_disabled");
                            location.href = data.url;
                        }else if(payType=="delivery"){
                            me.sendNotice();
                        }else if(payType=='alipay'){
                            if(window.browser==1){
                                var p = {
                                    "id": window.orderId,
                                    type: 'alipay'
                                };
                                location.href = window.hrefPath + '&module=product&method=orderBrowserOpen&params=' + encodeURIComponent(JSON.stringify(p));
                            }else{
                                location.href=data.url;
                            }
                        } else {
                            btn.removeClass("btn_disabled");
                            $.util.alert("支付方式错误");
                        }
                    },
                    error: function() {
                        btn.removeClass("btn_disabled");
                        $.util.alert("购买失败");
                    }
                });
            }
        },
        sendNotice:function(){
            var pa = {
                "id": window.orderId,
                "tplid": 1
            };
            if (window.isTeamPro == "1") {
                pa = {
                    "teamId": window.teamId,
                    "id": window.orderId
                }
            }
            if (window.isfreebuy == "1") {
                pa = {
                    "oid": window.orderId
                }
            }
            if(window.orderType == "3"){
                pa={
                    "parId":window.playOrderId,
                    "id": window.orderId
                }
            }
            $.ajax({
                url: window.basePath,
                dataType: "json",
                type: "POST",
                data: {
                    module: 'product',
                    method: 'sendNotice',
                    params: JSON.stringify(pa)
                },
                success: function(data) {
                    if (window.isfreebuy == "1") {
                        location.href = window.hrefPath + '&module=freebuy&method=getView&params=' + encodeURIComponent(JSON.stringify(pa));
                    } else if (window.isTeamPro == "1") {
                        location.href = window.hrefPath + '&module=tuan&method=getView&params=' + encodeURIComponent(JSON.stringify(pa));
                    }else if(window.orderType == "3"){
                        location.href = window.hrefPath + '&module=allChips&method=indianaSuccess&params=' + encodeURIComponent(JSON.stringify(pa));
                    }else if(window.isVirtual==1){
                        location.href = window.hrefPath + '&module=product&method=virtualSuccess&params=' + encodeURIComponent(JSON.stringify(pa));
                    } else {
                        if(data.sendId){
                            pa.sendId=data.sendId
                        }
                        location.href = window.hrefPath + '&module=product&method=orderSuccess&params=' + encodeURIComponent(JSON.stringify(pa));
                    }
                }
            });
        },
        cancelOrder: function(callback) {
            var btn = $(".btn-pay");
            $.ajax({
                url: window.basePath,
                dataType: "json",
                type: "POST",
                data: {
                    module: 'product',
                    method: 'cancelWxOrder',
                    params: '{"oid":' + window.orderId + '}'
                },
                success: function() {
                    btn.removeClass("btn_disabled");
                    callback && callback();
                }
            });
        },
        /**
         * [initAddr 初始化地址选择]
         * @return {[type]}
         */
        initAddr: function() {
            var payType = "wxpay";
            var params = {
                "tplid": 1,
                "orderId": orderId,
                "payType": payType
            };
            if (window.rootId) {
                params.rootId = rootId;
            }
            var editAddrUrl = window.hrefPath + '&module=product&method=getAddr&params=' + JSON.stringify(params);
            if (utils.isWeiXin()) {
                $.ajax({
                    url: window.basePath,
                    dataType: "json",
                    type: "POST",
                    timeout: 15000,
                    data: {
                        'module': 'product',
                        'method': 'getAddrSign',
                        'params': JSON.stringify({
                            "url": encodeURIComponent(document.location.href)
                        })
                    },
                    success: function(data) {
                        if (data && !data.code) {
                            try {
                                WeixinJSBridge.invoke('editAddress', {
                                    "appId": data.appId,
                                    "scope": data.scope,
                                    "signType": data.signType,
                                    "addrSign": data.addrSign,
                                    "timeStamp": data.timeStamp,
                                    "nonceStr": data.nonceStr
                                }, function(res) {
                                    if (res.err_msg != 'edit_address:ok') {
//                                      if (res.err_msg == 'edit_address:fail') {
//                                          return;
//                                      } else {
//                                          //微信中编辑地址失败则使用
//                                          var param = window.id == '' ? '' : ',"oid":' + window.id;
//                                          location.href = editAddrUrl;
//                                      }
										 //微信中编辑地址失败则使用
                                          //  var param = window.id == '' ? '' : ',"oid":' + window.id;
                                          //  location.href = editAddrUrl;
                                            m_citys.init();
                                            return;
                                    }

                                    window.fullName = res.userName || "";
                                    window.phone = res.telNumber || "";
                                    var addr = "";
                                    addr += res.addressDetailInfo;
                                    window.province = res.proviceFirstStageName || "";
                                    window.city = res.addressCitySecondStageName || "";
                                    window.country = res.addressCountiesThirdStageName || "";
                                    var temp =window.province+window.city+window.country;
                                    addr.indexOf(temp)>=0?addr.replace(temp,''):"";
                                    window.address = addr || "";
                                    var bp = {
                                        'module': 'product',
                                        'method': 'updateWeixinAddress',
                                        'params': '{"fullname":"' + window.fullName.replace(/\s+/g, "") +
                                            '","phone":"' + window.phone.replace(/\s+/g, "") +'","province":"'+res.proviceFirstStageName+
                                            '","city":"'+ res.addressCitySecondStageName+'","country":"'+ res.addressCountiesThirdStageName+
                                            '","isAcitivity":"'+window.isActivity+'","address":"' + window.address.replace(/\s+/g, "") +
                                            '","deliverytype":"delivery"}'
                                    };
                                    $.ajax({
                                        url: 'call.json?customerId=' + hrefParamsArray["customerId"],
                                        dataType: "json",
                                        type: "POST",
                                        data: bp,
                                        success: function(br) {
                                            $("#selDelivery").hide();
                                            $("#submitOrderwxpay").addClass("disabled").removeAttr("id");
                                            location.reload();
                                        }
                                    });


                                });
                            } catch (e) {
                                $.util.alert("操作失败，请确保在微信浏览器中操作");
                                return false;
                            }
                        } else {
                            m_citys.init();
                            return;
                        }
                    }
                });
            } else {
                m_citys.init();
                return;
            }
        }
    }
})(mi);
